using Godot;
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;

public partial class PikaFish : Node
{
	private Process _process;
	private StreamWriter _writer;
	[Signal] public delegate void SendMessageEventHandler(string message);
	public void Start(){
		StartCppProcess();
	}
	private void StartCppProcess()
	{
		ProcessStartInfo startInfo = new ProcessStartInfo
		{
			FileName = ".//引擎//pikafish-avx2.exe",	// 引擎路径
			RedirectStandardInput = true,			// 开启:重定向输入
			RedirectStandardOutput = true,			// 开启:重定向输出
			UseShellExecute = false,					// 不适用操作系统Shell执行的方式来运行进程
			CreateNoWindow = true					// 不创建窗口
		};
		_process = new Process { StartInfo = startInfo };
		_process.OutputDataReceived += (sender, e) =>
		{
			if (e.Data != null)
			{
				string[] words = e.Data.Split('\n'); 
				foreach (string word in words)
				{
					Callable.From(() => EmitSignal(SignalName.SendMessage, word)).CallDeferred();
				}			
			}
		};
		_process.Start();
		_process.BeginOutputReadLine();
		_writer = _process.StandardInput;
	}
	public void SendCommand(string command)
	{
		if (_writer != null && !_process.HasExited)
		{
			_writer.WriteLine(command);
		}
	}
}
